package fr.esiag.projet17.rmi;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Properties;

import fr.esiag.projet17.persistence.dao.ADAOFactory;
import fr.esiag.projet17.persistence.dao.factory.FactoryType;
import fr.esiag.projet17.persistence.dao.oracle.DAOFactory;
import fr.esiag.projet17.service.IDAOService;
import fr.esiag.projet17.service.utilisateur.IUtilisateurService;
import fr.esiag.projet17.service.utilisateur.UtilisateurService;

public class Server {

	protected static Properties props;

	static {
		props = new Properties();
		InputStream input;
		try {
			input = Server.class.getResourceAsStream("rmi_services.properties");
			props.load(input);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		System.out.println("Server rmi");
		Server monServer = new Server();
		System.out.println("Service user lié au registre");
	}

	public Server() {
		DAOFactory oracleDao = (DAOFactory) ADAOFactory
				.getDAOFactory(FactoryType.ORACLE);
		try {
			if (System.getSecurityManager() == null)
				System.setSecurityManager(new RMISecurityManager());
			
			IUtilisateurService userDAO = new UtilisateurService(oracleDao);
			IUtilisateurService stub = (IUtilisateurService) UnicastRemoteObject.exportObject(userDAO, 0);
			
			Integer port = Integer.parseInt(props.getProperty("rmi.port"));
			String url = props.getProperty("rmi.protocol")+ props.getProperty("rmi.host") +":"+ props.getProperty("rmi.port");
			Registry registry = LocateRegistry.getRegistry(props.getProperty("rmi.host"), port);
			registry.rebind(url+props.getProperty("rmi.service.utilisateur"), userDAO);

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
